package com.sgb.kjwl.view.ui.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.bumptech.glide.Glide;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.chuanglan.shanyan_sdk.listener.OneKeyLoginListener;
import com.chuanglan.shanyan_sdk.listener.OpenLoginAuthListener;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.sgb.alimaplibrary.MapLocationTools;
import com.sgb.auction.activity.AuctionHallActivity;
import com.sgb.auction.fragment.AuctionHallFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.FragmentMainRecruitmentBinding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.kjwl.model.entity.BannerEntity;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.view.event.special.QuickEntryEvent;
import com.sgb.kjwl.view.ui.activity.pick.PickHallActivity3;
import com.swgk.core.base.AppFragment;
import com.swgk.core.view.adapter.CommPagerAdapter;
import com.swgk.core.view.entity.EnterpriseEditEntity;
import com.swgk.core.view.entity.HomeManageMenuEntity;
import com.sgb.kjwl.model.entity.home.MenuManageEntity;
import com.sgb.kjwl.view.ui.activity.pick.PickListActivity;
import com.sgb.kjwl.view.ui.activity.pick.PickMapActivity;
import com.swgk.core.view.weiget.BigHomeComparyWidget;
import com.swgk.core.view.entity.MenuEntity;
import com.sgb.kjwl.model.entity.ProvinceEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.home.PictureEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.swgk.core.util.ACAdminDialogUtils;
import com.sgb.kjwl.utils.ConfigUtils;
import com.swgk.core.util.UiUtil;
import com.sgb.kjwl.view.event.ChooseAreaEvent;
import com.sgb.kjwl.view.event.CustomViewsInfo;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.event.self.MachinePublishEvent;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.activity.ScanActivity;
import com.sgb.kjwl.view.ui.activity.home.ChooseAreaActivity;
import com.sgb.kjwl.view.ui.activity.material.hall.NewPickHallFragment;
import com.sgb.kjwl.view.ui.activity.pick.PickBiddingListActivity;
import com.sgb.kjwl.view.ui.activity.pick.PickCompanyListActivity;
import com.sgb.kjwl.view.ui.activity.pick.PickHallSceneBidingActivity;
import com.sgb.kjwl.view.ui.activity.pick.PickNoticeActivity;
import com.sgb.kjwl.view.ui.activity.pick.PickWinningNoticeActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.home.HomePicturePickAdapter;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.ui.fragment.home.PickListFragment;
import com.swgk.core.view.weiget.CountMenuView;
import com.sgb.kjwl.view.widget.PickHallBidingPopWindow;
import com.sgb.kjwl.viewmodel.home.MainRecruitmentModel;
import com.sgb.zhaocai.view.demand.activity.DemandForecastActivity;
import com.sgb.zhaocai.view.demand.fragment.DemandForecastFragment;
import com.stx.xhb.androidx.XBanner;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.refresh.SuperSwipeRefreshLayout;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.util.SharedPreferenceUtil;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Description: 招采首页
 * Author CFK
 * Time
 */
@Route(path = AppRouteConstant.ZhaoCai.ROUTER_PATH_ZC_MAINRECRUITMENTFRAGMENT)
public class MainRecruitmentFragment extends AppFragment {
    public static final String KEY_TYPE = "type";
    private String type = "pickHall";
    private FragmentMainRecruitmentBinding binding;
    private MainActivity activity;
    private int select = 0;
    private boolean isCreate = false;
    private boolean init = true;
    private boolean isVisible;
    @Inject
    MainRecruitmentModel viewModel;
    private CommPagerAdapter pagerAdapter;
    private ArrayList<Fragment> mFragments;
    String[] stringName = new String[]{"招标信息", "正在招标", "竞价采购", "竞拍业务","需求计划", "中标公告", "招采企业", "知识分享"};
    String[] stringCode = new String[]{"pickHall", "homeHot", "openBid","paimaidating", "xuqiuyugao", "pickWinningNotice", "companyInfo", "share"};
    String[] stringOneName = new String[]{"全部", "招标公告", "直接竞价", "招标预告"};
    private List<PickSelectEntity> typeDataHot = new ArrayList<>();
    private List<PickSelectEntity> typeDataPickInfo = new ArrayList<>();
    private List<PickSelectEntity> tabTypeTwoList = new ArrayList<>();

    private PickHallBidingPopWindow pickTabLayoutPopWindow;
    private int tabPosition;
    private int tabTypeTwoPosition;
    private String typeNo;
    private int tabHallPosition;
    private MapLocationTools mapLocationTools;
    private List<PictureEntity> pictureEntityList = new ArrayList<>();
    private List<MenuEntity> menuEntityList = new ArrayList<>();
    private HomePicturePickAdapter homePicturePickAdapter;

    private ProgressBar progressBar;
    private TextView textView;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof MainActivity) {
            activity = (MainActivity) context;
        }
    }

    public static MainRecruitmentFragment newInstance(String type) {
        MainRecruitmentFragment fragment = new MainRecruitmentFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
        if (!isCreate) {
            return;
        }
        if (isVisibleToUser) {
            if (init) {
                init = false;
                init();
            }
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        isCreate = true;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_main_recruitment, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initView();
        if (init && isVisible) {
            init = false;
            init();
        }
    }

    public void setExpanded(boolean expanded) {
        binding.appBarLayout.setExpanded(expanded);
    }

    private void initView() {
        binding.appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset<-500){
                    binding.imgBackTop.setVisibility(View.VISIBLE);
                }else {
                    binding.imgBackTop.setVisibility(View.GONE);
                }
            }
        });

        binding.imgBackTop.setOnClickListener(v -> {
            ViewGroup.LayoutParams layoutParams = binding.appBarLayout.getLayoutParams();
            AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) ((CoordinatorLayout.LayoutParams) layoutParams).getBehavior();
            if (behavior != null) {
                float y = binding.calendarMenuView.getY();
                behavior.setTopAndBottomOffset((int) -y);
                binding.swipeRefresh.setEnabled(true);
                binding.imgBackTop.setVisibility(View.GONE);
            }
        });

        binding.ivQuickEntry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().postSticky(new QuickEntryEvent(binding.ivQuickEntry,null));
            }
        });

        binding.cityView.setOnClickListener(this);
        binding.scanView.setOnClickListener(this);
        binding.backView.setOnClickListener(this);
        binding.surveyView.setOnClickListener(this);
        binding.rlMapList.setOnClickListener(this);
        binding.swipeRefresh.setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onRefresh() {
                if (mFragments != null && mFragments.size() > 0) {
                    int position = binding.tabLayout.getSelectedTabPosition();
                    MLog.d("招采大厅", "开始刷新 当前所在界面 position=" + position);
                    textView.setText("正在刷新");
                    if (mFragments.get(position) instanceof NewPickHallFragment){
                        NewPickHallFragment newPickHallFragment = (NewPickHallFragment) mFragments.get(position);
                        newPickHallFragment.onPullRefresh(binding.swipeRefresh);
                    }else if (mFragments.get(position) instanceof PickListFragment){
                        PickListFragment pickListFragment = (PickListFragment) mFragments.get(position);
                        pickListFragment.onPullRefresh(binding.swipeRefresh);
                    } else if (mFragments.get(position) instanceof DemandForecastFragment){
                        DemandForecastFragment DemandForecastFragment = (DemandForecastFragment) mFragments.get(position);
                        DemandForecastFragment.onPullRefresh(binding.swipeRefresh);
                    }else if (mFragments.get(position) instanceof AuctionHallFragment){
                        AuctionHallFragment AuctionHallFragment = (AuctionHallFragment) mFragments.get(position);
                        AuctionHallFragment.onPullRefresh(binding.swipeRefresh);
                    }
                    //获取首页企业推荐
                    viewModel.getCompanyTitleList("onRefresh");
                } else {
//                    viewModel.getBannerModel();
//                    viewModel.getMenuModel();
                    showTabLayoutView();
                    viewModel.getPickMenuList();
                }
                Observable.timer(2000, TimeUnit.MILLISECONDS)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> {
                            binding.swipeRefresh.setRefreshing(false);
                        });
            }

            @Override
            public void onPullDistance(int distance) {
            }

            @Override
            public void onPullEnable(boolean enable) {
                textView.setText(enable ? "释放立即刷新" : "下拉刷新");
            }
        });
    /*    binding.appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
                if (i >= 0) {
                    binding.swipeRefresh.setEnabled(true);
                } else {
                    binding.swipeRefresh.setEnabled(false);
                }

            }
        });*/
        binding.swipeRefresh.setHeaderView(createHeaderView());
        binding.appBarLayout.addOnOffsetChangedListener((appBarLayout, i) -> {
            binding.swipeRefresh.setEnabled(i >= 0);
        });
        binding.appBarLayout.post(this::setAppbarDragCallback);

    }

    /**
     * 初始化首页企业推荐界面
     */
    public void initCompanyTitle(List<EnterpriseEditEntity> data) {
        if (binding == null) return;
        vsCompany = binding.vsCompany.getViewStub();
        if (vsCompany != null)
            vsCompany.inflate();
        if (vsCompany != null) {
            inflatedCompany = binding.getRoot().findViewById(R.id.inflatedCompany);
            bigHomeCompary = new BigHomeComparyWidget(this, inflatedCompany);
        }
        if (bigHomeCompary != null) {
            bigHomeCompary.unInit();
        }
        if (data == null || data.size() == 0) return;
        bigHomeCompary.initData(data);
        boolean isType = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.DisplaySettingsType, true);
        boolean isQY = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.DisplaySettingsQY, true);
        bigHomeCompary.setIsAotu(isType, isQY);
    }

    private void setAppbarDragCallback() {
        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) binding.appBarLayout.getLayoutParams();
        AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();
        if (behavior != null) {
            behavior.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
                @Override
                public boolean canDrag(@NonNull AppBarLayout appBarLayout) {
                    return true;
                }
            });
        }
    }

    private View createHeaderView() {
        View headerView = LayoutInflater.from(binding.swipeRefresh.getContext())
                .inflate(R.layout.super_swipe_refresh_head, null);
        progressBar = (ProgressBar) headerView.findViewById(R.id.pb_view);
        textView = (TextView) headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        progressBar.setVisibility(View.GONE);
        return headerView;
    }

    private void init() {
//        viewModel.getBannerModel();
//        viewModel.getMenuModel();
        //获取首页企业推荐
        viewModel.getCompanyTitleList("init");
        viewModel.getPickMenuList();
        showImageView();
        showTabLayoutView();
        showAreaName();

    }

    public void showAreaName() {
        binding.cityView.setText(viewModel.getAreaNameModel());
    }


    public void showBannerView(List<BannerEntity> bannerData) {
        binding.swipeRefresh.setRefreshing(false);
        ArrayList<CustomViewsInfo> imageListNo = new ArrayList<>();
        for (BannerEntity entity : bannerData) {
            imageListNo.add(new CustomViewsInfo(entity.getImgUrl()));
        }
        binding.banner.setBannerData(imageListNo);
        //加载广告图片
        binding.banner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                Glide.with(UiUtil.getContext()).load(imageListNo.get(position)).into((ImageView) view);
            }
        });
    }

    public void showMenuView(MenuManageEntity<List<HomeManageMenuEntity>> menuManageEntity) {
        List<MenuEntity> menuEntityList = new ArrayList<>();
        if (menuManageEntity.getData() != null) {
            for (int i = 0; i < menuManageEntity.getData().size(); i++) {
                MenuEntity entity = new MenuEntity();
                entity.setAppIcon(menuManageEntity.getData().get(i).getIconUrl());
                entity.setAppIconUrl(menuManageEntity.getData().get(i).getIconUrl());
                entity.setId(menuManageEntity.getData().get(i).getCode());
                entity.setUrl(menuManageEntity.getData().get(i).getIconUrl());
                if (menuManageEntity.getData().get(i).getName().length() > 6) {
                    String name = menuManageEntity.getData().get(i).getName().substring(0, 5) + "...";
                    entity.setName(name);
                } else {
                    entity.setName(menuManageEntity.getData().get(i).getName());
                }
                menuEntityList.add(entity);
            }
        }
        binding.swipeRefresh.setRefreshing(false);
        binding.calendarMenuView.setRowAndColumn(menuManageEntity.getRowNum(),menuManageEntity.getNum());
        binding.calendarMenuView.initData(getChildFragmentManager(), menuEntityList, new CountMenuView.OnItemClick(){
            @Override
            public void onItemClick(MenuEntity entity, int position, int num) {
                String[] strings = entity.getId().split("_");
                PickListActivity.start(activity,"1",Integer.valueOf(strings[0]) + 1);
            }
        });
    }

    public void showImageView() {
        if (pictureEntityList.size() == 0) {
            pictureEntityList.add(new PictureEntity("招标大厅", "bq_zbdt"));
            pictureEntityList.add(new PictureEntity("招标公告", "bq_zbgg"));
            pictureEntityList.add(new PictureEntity("直接竞价", "bq_zjjj"));
            pictureEntityList.add(new PictureEntity("拍卖大厅", "bq_pmdt"));
            pictureEntityList.add(new PictureEntity("需求预告", "bq_xqyg"));
            pictureEntityList.add(new PictureEntity("招标预告", "bq_zbyg"));
            pictureEntityList.add(new PictureEntity("招采企业", "bq_qyzx"));
            pictureEntityList.add(new PictureEntity("中标公告", "bq_zbgg1"));
//            pictureEntityList.add(new PictureEntity("招标信息", "bq_zbxx"));
            pictureEntityList.add(new PictureEntity("现场竞标", "bq_xcjb"));
        }
        homePicturePickAdapter = new HomePicturePickAdapter(getContext(), pictureEntityList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        binding.recyclerViewImg.setLayoutManager(linearLayoutManager);
        binding.recyclerViewImg.setAdapter(homePicturePickAdapter);
        homePicturePickAdapter.setOnItemClick(new AdapterOnItemClick<PictureEntity>() {
            @Override
            public void onItemClick(PictureEntity pictureEntity, int position) {
                switch (position) {
                    case 0: //招标大厅
                        PickListActivity.start(activity,"1",0);
                        break;
                    case 1: //招标公告
                        PickListActivity.start(activity,"2",0);
                        break;
                    case 2: //竞价采购
                        PickBiddingListActivity.start(activity); //竞价采购
                        break;
                    case 3: //拍卖大厅
                        AuctionHallActivity.start(activity,"1");
                        break;
                    case 4: //需求预告
                        DemandForecastActivity.start(activity);
                        break;
                    case 5: //招标预告
                        PickNoticeActivity.start(activity); //招标预公告
                        break;
                    case 6: //招采企业
                        PickCompanyListActivity.start(activity); //招采企业
                        break;
                    case 7: //中标公告
                        PickWinningNoticeActivity.start(activity); // 中标公告
                        break;
//                        case 7: //招标信息
//                            PickInfoActivity.start(activity); //招标信息
//                            break;
                    case 8: //现场竞标
                        PickHallSceneBidingActivity.start(activity);
                        break;
//                        case "11": //投标查询
//                            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
//                                jumpLogin();
//                            } else {
//                                jumpH5("tenderList", "", MK_7_TOUBIAOCHAXUN);
//                            }
//                            break;
//                        case "12": //竞价查询
//                            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
//                                jumpLogin();
//                            } else {
//                                jumpH5("bidList", "", MK_7_JINGJIACHAXUN);
//                            }
//                            break;
//                        case "14": //智能关注
//                            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
//                                jumpLogin();
//                            } else {
//                                if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 1) {
//                                    viewModel.getCompanyList();
//                                } else {
//                                    IntelligentAttentionActivity.start(activity, 2);
//                                }
//                            }
//                            break;
                }
            }
        });
    }

    private void jumpH5(String param, String urlId, String tag) {
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        if ("".equals(companyNo) || "0".equals(companyNo)) {  //个人
            viewModel.getStringUrl(param, "");
        } else {
            if (ACAdminDialogUtils.isPermission(tag, false) == ACAdminDialogUtils.TYPE_NO_PERMISSION) {
                MToast.showLongToast(getActivity(), "您没有权限，请联系管理员开通");
            } else {
                viewModel.getStringUrl(param, urlId);
            }
        }
    }

    public void showTabLayoutView() {
        if (binding == null || binding.swipeRefresh == null) return;
        binding.swipeRefresh.setRefreshing(false);
        int num = stringName.length;
        mFragments = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            if (i == 0) {
                mFragments.add(NewPickHallFragment.newInstance("0"));
            } else if (i == 1) {
                mFragments.add(NewPickHallFragment.newInstance("1"));
            } else if (i == 3) {//拍卖大厅
                mFragments.add(AuctionHallFragment.newInstance("1",""));
            } else if (i == 4) {//需求预告
                mFragments.add(DemandForecastFragment.newInstance());
            } else  {
                mFragments.add(PickListFragment.newInstance(stringCode[i]));
            }
        }
        pagerAdapter = new CommPagerAdapter(getChildFragmentManager(), mFragments, stringName);
        binding.viewpager.setAdapter(pagerAdapter);
//        binding.viewpager.setOffscreenPageLimit(num);
        binding.tabLayout.setupWithViewPager(binding.viewpager);

        for (int i = 0; i < stringName.length; i++) {
            binding.tabLayout.getTabAt(i).setCustomView(R.layout.tab_item_textview);
            TextView tv = binding.tabLayout.getTabAt(i).getCustomView().findViewById(R.id.tv_tab_item_textview);
            tv.setText(stringName[i]);
            if (i == 0) {
                tv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                tv.setTextColor(getResources().getColor(R.color.color_main));
            }
            binding.tabLayout.getTabAt(0).select();
        }

//        for (int i = 0; i < stringOneName.length; i++) {
//            binding.tabLayoutTypeHall.addTab(binding.tabLayoutTypeHall.newTab().setText(stringOneName[i]));
//        }

        binding.tabLayout.addOnTabSelectedListener(tabSelectedListener);
//        binding.tabLayoutTypeHall.addOnTabSelectedListener(tabTypeHallSelectedListener);
        binding.tabLayoutTypeTwo.addOnTabSelectedListener(tabTypeTwoSelectedListener);

        pickTabLayoutPopWindow = new PickHallBidingPopWindow(getActivity());
        pickTabLayoutPopWindow.setOnResultClick((key1, key2, key3) -> {
            binding.tabLayoutTypeTwo.getTabAt((int) key3).select();
            pickTabLayoutPopWindow.setDefItem((int) key3);
            Fragment fragment = mFragments.get(tabPosition);
            if (fragment instanceof PickListFragment) {
                ((PickListFragment) fragment).setTypeNo(stringOneName[tabHallPosition], typeNo, ((PickSelectEntity) key1).getNo(), type);
            }
        });
        pickTabLayoutPopWindow.setOnDisMissClick(() -> {
            binding.surveyView.setImageResource(R.drawable.btn_down);
        });
    }

    private final TabLayout.OnTabSelectedListener tabSelectedListener = new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            if (tab != null && tab.getCustomView() != null) {
                TextView tabSelect = tab.getCustomView().findViewById(R.id.tv_tab_item_textview);
                tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                tabSelect.setTextColor(getResources().getColor(R.color.color_main));
                tabSelect.invalidate();
            }
            tabPosition = tab.getPosition();
            type = stringCode[tabPosition];
            if (tabPosition == 2 || tabPosition == 5) {   //中标公告，竞价采购有2级
                binding.lineTabType.setVisibility(View.VISIBLE);
                if (typeDataHot == null || typeDataHot.size() == 0) {
                    viewModel.getFilterTypeData();
                } else {
                    setTabTypeData(typeDataHot, binding.tabLayoutType);
                }
            } else {
                binding.lineTabType.setVisibility(View.GONE);
                binding.lineTabTypeTwo.setVisibility(View.GONE);
                if (tabPosition != 3 && tabPosition != 4){//拍卖和需求预告
                    Fragment fragment = mFragments.get(tabPosition);
                    if (tabPosition == 0) {
                        ((NewPickHallFragment) fragment).setTypeNo("0");
                    } else if (tabPosition == 1) {
                        ((NewPickHallFragment) fragment).setTypeNo("1");
                    } else {
                        ((PickListFragment) fragment).setTypeNo("", "", "", type);
                    }
                }
            }
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            TextView tabSelect = tab.getCustomView().findViewById(R.id.tv_tab_item_textview);
            tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            tabSelect.setTextColor(getResources().getColor(R.color.color_tab_one));
            tabSelect.invalidate();

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };


//    private final TabLayout.OnTabSelectedListener tabTypeHallSelectedListener = new TabLayout.OnTabSelectedListener() {
//        @Override
//        public void onTabSelected(TabLayout.Tab tab) {
//            tabHallPosition = tab.getPosition();
//            if (tabHallPosition == 0) {
//                binding.tabLayoutType.setVisibility(View.GONE);
//                Fragment fragment = mFragments.get(0);
//                if (fragment instanceof PickListFragment) {
//                    ((PickListFragment) fragment).setTypeNo(stringOneName[tabHallPosition], "", "", type);
//                }
//            } else {
//                binding.tabLayoutType.setVisibility(View.VISIBLE);
//                if (tab.getPosition() == 2) {
//                    if (typeDataBidding == null || typeDataBidding.size() == 0) {
//                        viewModel.getFilterTypeBiddingData();
//                    } else {
//                        setTabTypeData(typeDataBidding, binding.tabLayoutType);
//                    }
//                } else {
//                    if (typeDataHot == null || typeDataHot.size() == 0) {
//                        viewModel.getFilterTypeData();
//                    } else {
//                        setTabTypeData(typeDataHot, binding.tabLayoutType);
//                    }
//                }
//            }
//
//        }
//
//        @Override
//        public void onTabUnselected(TabLayout.Tab tab) {
//
//        }
//
//        @Override
//        public void onTabReselected(TabLayout.Tab tab) {
//
//        }
//    };

    private final TabLayout.OnTabSelectedListener tabTypeSelectedListener = new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            if (tab != null && tab.getCustomView() != null) {
                TextView tabSelect = tab.getCustomView().findViewById(R.id.tv_tab_item_textview);
                tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                tabSelect.setTextColor(getResources().getColor(R.color.color_main));
                tabSelect.invalidate();
            }
            int position = tab.getPosition();
            tabSelecter(position);
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            if (tab != null && tab.getCustomView() != null) {
                TextView tabSelect = tab.getCustomView().findViewById(R.id.tv_tab_item_textview);
                tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                tabSelect.setTextColor(getResources().getColor(R.color.color_tab_one));
                tabSelect.invalidate();
            }
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };

    private final TabLayout.OnTabSelectedListener tabTypeTwoSelectedListener = new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            tabTypeTwoPosition = tab.getPosition();
            pickTabLayoutPopWindow.setDefItem(tabTypeTwoPosition);
            Fragment fragment = mFragments.get(tabPosition);
            if (binding.lineTabTypeTwo.getVisibility() == View.VISIBLE) {
                if (fragment instanceof PickListFragment) {
                    ((PickListFragment) fragment).setTypeNo(stringOneName[tabHallPosition], typeNo, tabTypeTwoList.get(tabTypeTwoPosition).getNo(), type);
                }
            }

        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };

    /**
     * 招标大厅下tab滑动切换
     */
    public void changeTabLayoutTypeHall(String typeNoOnePosition) {
        for (int i = 0; i < stringOneName.length; i++) {
            if (typeNoOnePosition.equals(stringOneName[i]) && i < (stringOneName.length - 1)) {
//                binding.tabLayoutTypeHall.getTabAt(i + 1).select();
            }
        }
    }

    /**
     * 二级分类
     */
    public void setTenderGoodsCategoryAllList(List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> datas) {
        tabTypeTwoList.clear();
        binding.tabLayoutTypeTwo.removeAllTabs();
        if (datas.size() != 0) {
            for (int i = 0; i < datas.size(); i++) {
                PickSelectEntity pickSelectEntity = new PickSelectEntity(datas.get(i).getNo(), datas.get(i).getProjectscale());
                tabTypeTwoList.add(pickSelectEntity);
                binding.tabLayoutTypeTwo.addTab(binding.tabLayoutTypeTwo.newTab().setText(pickSelectEntity.getProjectscale()));
            }
        } else {
            binding.lineTabTypeTwo.setVisibility(View.GONE);
        }
    }

    public void setTypeData(List<PickSelectEntity> datas) {
        typeDataHot.clear();
        typeDataHot.addAll(datas);
        setTabTypeData(typeDataHot, binding.tabLayoutType);
    }

    public void setTypePickInfoData(List<PickSelectEntity> datas) {
        PickSelectEntity entity = new PickSelectEntity("", "全部");
        datas.add(0, entity);
        typeDataPickInfo.clear();
        typeDataPickInfo.addAll(datas);
        setTabTypeData(typeDataPickInfo, binding.tabLayoutType);
    }

    private void setTabTypeData(List<PickSelectEntity> data, TabLayout tabLayout) {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showProgressDialog(getActivity(), "获取信息中...");
        }
        binding.tabLayoutType.clearOnTabSelectedListeners();
        binding.tabLayoutType.removeAllTabs();
        for (int i = 0; i < data.size(); i++) {
            binding.tabLayoutType.addTab(binding.tabLayoutType.newTab().setText(data.get(i).getProjectscale()));
        }
        binding.tabLayoutType.scrollTo(0, 0);
        binding.tabLayoutType.addOnTabSelectedListener(tabTypeSelectedListener);
        tabSelecter(0);
    }

    private void tabSelecter(int position) {
        if (typeDataHot == null || typeDataHot.size() <= 0) return;
        String typeNoOne = "";
        typeNo = "";
        Fragment fragment = mFragments.get(tabPosition);

        int isShow = 8;

        if ("openBid".equals(type)) {//竞价采购
            typeNo = typeDataHot.get(position).getNo();
            isShow = 0;
            if (position != 0) {
                viewModel.getTenderGoodsCategoryAllList(typeNo);
            }
        } else if ("pickInfo".equals(type)) {//招标信息
            typeNo = typeDataPickInfo.get(position).getProjectscale();
            isShow = 8;
        } else if ("pickWinningNotice".equals(type)) {//中标公告
            typeNo = typeDataHot.get(position).getNo();
            isShow = 0;
            if (position != 0) {
                viewModel.getTenderGoodsCategoryAllList(typeNo);
            }
        } else {
            isShow = 8;
        }

        if (position == 0 || "20".equals(typeNo)) {
            binding.lineTabTypeTwo.setVisibility(View.GONE);
        } else {
            tabTypeTwoList.clear();
            binding.tabLayoutTypeTwo.removeAllTabs();
            binding.lineTabTypeTwo.setVisibility(isShow);
        }

        if (binding.lineTabTypeTwo.getVisibility() == View.GONE) {
            if (fragment instanceof PickListFragment) {
                ((PickListFragment) fragment).setTypeNo(typeNoOne, typeNo, "", type);
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.city_view:
                ChooseAreaActivity.start(getActivity(), select);
                break;
            case R.id.scan_view:
                checkPermission();
                break;
            case R.id.back_view:
                activity.checkHome();
                break;
            case R.id.survey_view:
                if (tabTypeTwoList == null || tabTypeTwoList.size() == 0) return;
                binding.surveyView.setImageResource(R.drawable.btn_shop_up);
                pickTabLayoutPopWindow.showPopwindow(binding.surveyView);
                pickTabLayoutPopWindow.setData(tabTypeTwoList, binding.tabLayoutTypeTwo.getSelectedTabPosition());
                break;
            case R.id.rl_map_list:
                PickMapActivity.start(getActivity());
                break;
        }
    }

//    /**
//     * 显示公司列表
//     *
//     * @param data
//     */
//    public void showCompanyList(List<CompanyEntity> data) {
//        if (data != null && data.size() > 0) {
//            for (CompanyEntity companyEntity : data) {
//                if (companyEntity.getType() != 1) {
//                    viewModel.settingMainCompany(companyEntity);
//                    viewModel.getEssentialInformation(companyEntity);
//                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COM_TYPE, companyEntity.getType());
//                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COMPANY_NO, companyEntity.getCompNo());
//                    EventBus.getDefault().postSticky(EventConstant.EVENT_REFRESH_MAIN);
//                    IntelligentAttentionActivity.start(activity, 2);
//                }
//            }
//        }
//    }

//    // 设置主企业
//    public void setCurrentCompany(CompanyEntity companyEntity) {
//        EventBus.getDefault().postSticky(MainEvent.make(EventConstant.EVENT_MAIN_ENTERPRISE_SWITCHING, 0));
//    }
/*
    public void scrollToTop() {
        //拿到 appbar 的 behavior,让 appbar 滚动
        ViewGroup.LayoutParams layoutParams = binding.appBarLayout.getLayoutParams();
        AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) ((CoordinatorLayout.LayoutParams) layoutParams).getBehavior();
        if (behavior != null) {
            //拿到下方tabs的y坐标，即为我要的偏移量
            float y = binding.headerLayout.getY();
            //注意传递负值
            behavior.setTopAndBottomOffset((int) -y);
            isExpanded = true;
        }
    }*/

    private void checkPermission() {
        if (PermissionsUtil.hasPermission(getActivity(), Manifest.permission.CAMERA)) {
            ScanActivity.start(getActivity());
        } else {
            PermissionsUtil.requestPermission(getActivity(), new PermissionListener() {
                @Override
                public void permissionGranted(@NonNull String[] permissions) {
                    ScanActivity.start(getActivity());
                }

                @Override
                public void permissionDenied(@NonNull String[] permissions) {
                    MToast.showLongToast(getActivity(), "请先获取相机权限");
                }
            }, Manifest.permission.CAMERA);
        }
    }

    public void showChangeDialog(ProvinceEntity provinceEntity) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        AlertDialog alertDialog = builder.setTitle("您当前位置在" + provinceEntity.getAreaName()).setMessage("是否确定切换到" + provinceEntity.getAreaName()).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                EventBus.getDefault().postSticky(ChooseAreaEvent.make(EventConstant.EVENT_CHOOSE_AERA, provinceEntity));
            }
        }).setCancelable(true).create();
        alertDialog.show();
        Window dialogWindow = alertDialog.getWindow();
        WindowManager m = activity.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        // 设置宽度
        p.width = (int) (d.getWidth() * 0.95); // 宽度设置为屏幕的0.95
        p.gravity = Gravity.CENTER;//设置位置
        //p.alpha = 0.8f;//设置透明度
        dialogWindow.setAttributes(p);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ChooseAreaEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CHOOSE_AERA) {
            //todo 城市切换暂时注释
            ProvinceEntity<List<ProvinceEntity>> list = (ProvinceEntity<List<ProvinceEntity>>) event.getMessageData();
            viewModel.saveProvinceModel(list.getShortName(), String.valueOf(list.getId()));
            //暂时获取全国数据，不需要随地区切换改变数据
            //init();
            //获取首页企业推荐
            viewModel.getCompanyTitleList("refreshHomeData");
        }
        if (event.getMessageTag() == EventConstant.EVENT_NOTICE_REFRESH_HOME) {
            bigHomeCompary.unInit();
            //获取首页企业推荐
            viewModel.getCompanyTitleList("EventConstant.EVENT_NOTICE_REFRESH_HOME");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LoginEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_MAIN_ACTIVITY_JUMP) {
//            viewModel.getRecommendListModel();
//            showTabLayoutView();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MachinePublishEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_LOGIN_OUT) {
//            viewModel.getRecommendListModel();
//            showTabLayoutView();
        }
    }

    /**
     * 获取当前经纬度
     */
    public void getLocation() {

        if (mapLocationTools == null) {
            mapLocationTools = new MapLocationTools(getContext());
        }
        mapLocationTools.initLocation(false);
        mapLocationTools.setLocationListener(new MapLocationTools.LocationListener() {
            @Override
            public void getLocationListener(String address, Double Longitude, Double Latitude) {
                SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LONGITUDE_ID, String.valueOf(Longitude));
                SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LATITUDE_ID, String.valueOf(Latitude));
            }
        });
        mapLocationTools.startLocation();

    }

    @Override
    public void onResume() {
        super.onResume();
        getLocation();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void jumpLogin() {
        boolean shanyan = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.ShanYan, false);
        if (shanyan) {
            //校验权限
            //申请动态权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //6.0以上运行时权限处理
                EsayPermissions.with(activity).constantRequest().permission(PERMISSIONS).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        openLoginPage();
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        openLoginPage();
                    }
                });

            } else {
                //有权限
                openLoginPage();
            }

        } else {
            VerificationCodeLoginActivity.start(activity, EventConstant.EVENT_TENDER_DETAILS_3_JUMP);
        }
    }

    //闪验
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE
    };

    /**
     * 拉起授权页
     */
    private void openLoginPage() {
        //设置授权页样式
        OneKeyLoginManager.getInstance().setAuthThemeConfig(ConfigUtils.getCJSConfig(activity));
        //开始拉取授权页
        DialogHelper.showProgressDialog(activity, null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(true);
        OneKeyLoginManager.getInstance().openLoginAuth(false, new OpenLoginAuthListener() {
            @Override
            public void getOpenLoginAuthStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code != 1000) {
                    VerificationCodeLoginActivity.start(activity, EventConstant.EVENT_TENDER_DETAILS_3_JUMP);
                }
            }
        }, new OneKeyLoginListener() {
            @Override
            public void getOneKeyLoginStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code == 1000) {
                    OneKeyLoginEntity oneKeyLoginEntity = GsonManager.getInstance().getGson().fromJson(result, OneKeyLoginEntity.class);
                    oneKeyLoginEntity.setPlateform("Android");
                    viewModel.oneKeyLogin(oneKeyLoginEntity);
                }
            }
        });
    }

    /**
     * 一键登录成功
     *
     * @param loginEntity
     * @param phoneNumber
     */
    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
        loginEvent.setMessageTag(EventConstant.EVENT_TENDER_DETAILS_3_JUMP);
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

}